import { Component, OnInit } from '@angular/core';
import { MgUser } from '../../domain/mguser';
import { ActivatedRoute } from '@angular/router';
import { UserService } from '../../service/user.service';
import { Toastr } from '../../common/toastr';
import { NavbarService } from '../../component/navbar/navbar.service';

@Component({
    moduleId: module.id,
    templateUrl: 'mguserEdit.component.html'
})
export class MguserEditComponent implements OnInit {
    private title: string = "新增或编辑管理员";
    private subTitle: string = "新增或编辑管理员信息";
    private mguser: MgUser = new MgUser();
    private confimPassword: string;
    constructor(
        private route: ActivatedRoute,
        private userSvr: UserService
    ) { }

    async ngOnInit() {
        try {
            let id = +this.route.snapshot.params['id'];
            if (id)
                this.mguser = await this.userSvr.GetMgUserInfo(id);
        } catch (error) {
            Toastr.Error(error);
        }
    }

    async okBtn() {
        try {
            this.checkMode();
            if (this.mguser.password != this.confimPassword) throw "密码和确认密码不一致！";
            await this.userSvr.SaveMgUser(this.mguser);
            NavbarService.Current.Navigate(['/main/mguser']);
        } catch (error) {
            this.mguser.password = "";
            this.confimPassword = "";
            Toastr.Error(error);
        }
    }

    checkMode(){
        if(!this.mguser.loginName) throw "未填写账号！";
        if(!this.mguser.password) throw "未填写密码！";
    }
}